package com.jack.concurrency;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhang_j on 2019/12/11
 */
public class MyThreadLocal {
    private static final ThreadPoolExecutor EXECUTOR_SERVICE = new ThreadPoolExecutor(100,120,60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build(),
            new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * threadLocal:1
     * threadLocal:1
     * threadLocal:1
     * noThreadLocal:1
     * noThreadLocal:2
     * noThreadLocal:3
     */
    public static void main(String[] args) {
        final ResultData resultData = new ResultData();
        EXECUTOR_SERVICE.execute(()->resultData.getNum());
        EXECUTOR_SERVICE.execute(()->resultData.getNum());
        EXECUTOR_SERVICE.execute(()->resultData.getNum());

        final NoThreadLocalResultData noThreadLocalResultData = new NoThreadLocalResultData();
        EXECUTOR_SERVICE.execute(()->noThreadLocalResultData.getNum());
        EXECUTOR_SERVICE.execute(()->noThreadLocalResultData.getNum());
        EXECUTOR_SERVICE.execute(()->noThreadLocalResultData.getNum());
    }

}
class NoThreadLocalResultData{
    public static Integer count=0;
    public Integer getNum() {
        count = count + 1;
        System.out.println("noThreadLocal:"+count);
        return count;
    }
}
class ResultData{
    // 生成序列号共享变量
    public static Integer count=0;
    private static ThreadLocal<Integer> threadLocal=new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };
    public Integer getNum() {
        int count = threadLocal.get() + 1;
        threadLocal.set(count);
        System.out.println("threadLocal:"+count);
        return count;
    }
}